package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Redis 配置
 *
 * @author SongRenShuo
 * @date 2023-12-28
 */
@Configuration
public class MyRedisConfig {

    /**
     * RedisTemplate 对象，用于操作 Redis 数据
     *
     * @param redisConnectionFactory Redis 连接工厂
     * @return Redis 模板<字符串、对象>
     */
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 初始化 RedisTemplate 对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置 key 序列化器
        redisTemplate.setKeySerializer(keySerializer());
        // 设置 hash key 序列化器
        redisTemplate.setHashKeySerializer(keySerializer());
        // 设置 value 序列化器
        redisTemplate.setValueSerializer(valueSerializer());
        // 设置 hash value 序列化器
        redisTemplate.setHashValueSerializer(valueSerializer());
        return redisTemplate;
    }


    /**
     * 缓存管理器 - 用于管理 Redis 缓存
     *
     * @param redisConnectionFactory Redis 连接工厂
     * @return 缓存管理器
     */
    @Primary
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 缓存配置对象
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

        // 设置缓存的默认超时时间：30分钟
        redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L))
                // 如果是空值，不缓存
                .disableCachingNullValues()
                // 设置key序列化器
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                // 设置value序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer())));

        // 返回 RedisCacheManager 对象
        return new RedisCacheManager(
                // 使用非锁定的 RedisCacheWriter
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                // 默认策略，未配置的 key 会使用这个
                this.getRedisCacheConfigurationWithTtl(60),
                // 指定 key 策略
                this.getRedisCacheConfigurationMap());
        // return
        // RedisCacheManager
        // .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
        // .cacheDefaults(redisCacheConfiguration).build();
    }


    /**
     * key 序列化器
     *
     * @return Redis 序列化程序<字符串>
     */
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }


    /**
     * value 序列化器
     *
     * @return Redis 序列化程序<对象>
     */
    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }


    /**
     * 自定义的缓存配置
     *
     * @return map<字符串 ， redis缓存配置>
     */
    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        // SsoCache和BasicDataCache进行过期时间配置
        redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60));

        // 自定义设置缓存时间
        redisCacheConfigurationMap.put("dept", this.getRedisCacheConfigurationWithTtl(60)); // 60秒

        return redisCacheConfigurationMap;
    }


    /**
     *  TTL 获取 Redis 缓存配置 - 获取带有过期时间的缓存配置
     *
     * @param seconds 秒
     * @return Redis 缓存配置
     */
    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }
}
